#pragma once

#include <iostream>
#include <vector>
#include <semaphore.h>
#include "lockGuard.hpp"

const int defaultsize = 5;

template<class T>
class ringqueue
{
private:
    void P(sem_t &sem)//P,V操作
    {
        sem_wait(&sem);
    }
    void V(sem_t &sem)
    {
        sem_post(&sem);
    }
public:
    ringqueue(int size = defaultsize)
    :_ringqueue(size),_size(size),_p_step(0),_c_step(0)
    {
        sem_init(&_space_sem, 0, size);
        sem_init(&_data_sem, 0, 0);

        pthread_mutex_init(&_c_mutex,NULL);
        pthread_mutex_init(&_p_mutex    ,NULL);  
    }
    void push(const T& in)
    {
        P(_space_sem);//同步操作
        {
            lockguard lg(&_p_mutex);
            _ringqueue[_p_step] = in;
            _p_step++;
            _p_step %= _size;
        }//作用外lg自动销毁
        V(_data_sem);
    }
    void pop(T* out)
    {
        P(_data_sem);
        {
            lockguard lg(&_c_mutex);
            *out = _ringqueue[_c_step];
            
            _c_step++;
            _c_step %= _size;
        }
        V(_space_sem);
    }
    ~ringqueue()
    {
        sem_destroy(&_space_sem);
        sem_destroy(&_data_sem);

        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }
private:
    std::vector<T> _ringqueue;
    int _size;

    int _p_step;
    int _c_step;

    sem_t _space_sem;
    sem_t _data_sem;

    pthread_mutex_t _p_mutex;
    pthread_mutex_t _c_mutex;
};